package com.sunzr0119.conventioncentertemplatebackend.service.impl;

import com.sunzr0119.conventioncentertemplatebackend.dao.UserDAO;
import com.sunzr0119.conventioncentertemplatebackend.dto.UserLoginDTO;
import com.sunzr0119.conventioncentertemplatebackend.dto.UserRegisterDTO;
import com.sunzr0119.conventioncentertemplatebackend.entity.User;
import com.sunzr0119.conventioncentertemplatebackend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.Objects;
import java.util.Optional;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserDAO userDAO;

    @Override
    public ResponseEntity<User> login(UserLoginDTO loginDTO) {
        User user = userDAO.findByEmail(loginDTO.getUserEmail());
        if(user == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
        }else {
            if(user.getPassword().equals(loginDTO.getUserPassword())){
                return ResponseEntity.status(HttpStatus.OK).body(user);
            }else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
            }
        }
    }

    @Override
    public ResponseEntity<String> register(UserRegisterDTO userRegisterDTO) {
        // 获取 Redis 中存储的验证码
        String storedCaptcha = redisTemplate.opsForValue().get("captcha:" + userRegisterDTO.getUserEmail());
        if (storedCaptcha != null && storedCaptcha.equals(userRegisterDTO.getUserEmailCaptcha())) {
            // 验证码匹配，注册可以继续
            if(userDAO.findByEmail(userRegisterDTO.getUserEmail()) != null) {
                return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("用户已存在！错误码：01.");
            }else{
                // 为文件分配一个唯一的 UUID
                String id = UUID.randomUUID().toString();
                String role;
                if(Objects.equals(userRegisterDTO.getInvitationToken(), "nnugis")){
                    role = "admin";
                }else{
                    role = "user";
                }
                User user = new User(userRegisterDTO);
                user.setId(id);
                user.setUserRole(role);
                User resUser = userDAO.save(user);
                return ResponseEntity.ok("用户注册成功！操作码：02.");
            }
        } else {
            // 验证码不匹配
            return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("验证码不匹配！错误码：03.");
        }
    }
}
